import { api, scheme } from '@/api/url'
/*global projectName:false*/

// 正在开启的定时器列表内容
window.AddEventBackList = {}

const appInfo = () => {
  const ua = window.navigator.userAgent
  const device = {
    isAndroid: ua.indexOf('Android') > -1 || ua.indexOf('Adr') > -1,
    isiOS: !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
    isIOSX: /iphone/gi.test(ua) && (window.screen.height == 812 && window.screen.width == 375)
  }
  if (/108sq/i.test(ua)) {
    const reg = /108sq\/([^/]*)\/([^/]*)\/([^/]*)\/([^/]*)$/i
    const match = ua.match(reg)
    return {
      ua: ua,
      name: '108sq',
      is108sq: true,
      version: match ? match[1] : '',
      siteId: match ? match[2] : '',
      channelName: match ? match[3] : '',
      netType: match ? match[4] : '',
      ...device
    }
  } else {
    return {
      ua: ua,
      name: 'error',
      is108sq: false,
      version: '0',
      siteId: '1',
      channelName: '0',
      netType: '0',
      ...device
    }
  }
}

function getJsbridgeValue (jsbridgeName) {
  let result = ''
  let func = async () => {
    result = await trigger(jsbridgeName)
  }
  func()
  return result
}

// 触发方法
async function trigger (funcName) {
  var args = Array.prototype.slice.call(arguments).slice(1)
  const callApp = await new Promise((resolve) => {
    let _callApp = window['ChangShuoJSBridge'] || ''
    // 如果jsbridge已经加载完毕
    if (_callApp !== '') {
      resolve(_callApp)
    } else {
      let time = 0
      const id = setInterval(() => {
        _callApp = window['ChangShuoJSBridge'] || ''
        // 如果jsbridge已经加载完毕
        if (_callApp !== '') {
          resolve(_callApp)
          clearInterval(id)
          return
        } else {
          if (time >= 3000) {
            // alert('jsbridge出错了，请检查！');
            resolve({})
            clearInterval(id)
            return
          }
        }
        time += 50
      }, 50)
    }
  })
  if (callApp[funcName]) {
    return callApp[funcName].apply(callApp, args)
  } else {
    return ''
  }
}

export default class App {
  static appInfo = appInfo()
  static getToken = () => {
    return getJsbridgeValue('getToken')
  }
  // 获取用户名
  static getUserName = async () => {
    return getJsbridgeValue('getUserName')
  }
  // 获取用户ID
  static getUserId = async () => {
    return getJsbridgeValue('getUserId')
  }
  static getUTDID = () => {
    return getJsbridgeValue('getUTDID')
  }
  // 获取设备号
  static getEncryptMobile = () => {
    return getJsbridgeValue('getEncryptMobile')
  }
  static hideMoreMenu = async () => {
    return await trigger('hideMoreMenu')
  }
  static appWebShare = async (opt) => {
    return await trigger('appWebShare', JSON.stringify(opt))
  }
  // 分享
  static shareWebPage = async (config) => {
    const defaultOpt = {
      title: '',
      titleUrl: '',
      content: '',
      imageUrl: '',
      shareType: 3,
      infoid: '',
      isImage: false,
      isNativeShare: false
    }
    config = {
      ...defaultOpt,
      ...config
    }
    return await trigger('shareWebPage', JSON.stringify(config))
  }
  // 打开新webview
  static openWebWindow = async (url = '', params = '') => {
    return await trigger('openWebWindow', `${window.location.origin}/${projectName}${url}`, params)
  }
  // 打开外网地址新webview
  static openOutNetWebWindow = async (url = '', params = '') => {
    return await trigger('openWebWindow', url, params)
  }
  // 关闭webview
  static closeWebWindow = async (config = {}) => {
    const defaultConfig = {
      name: '',
      count: ''
    }
    config = {
      ...defaultConfig,
      ...config
    }
    return await trigger('closeWebWindow', JSON.stringify(config))
  }
  // 埋点
  static webStatistics = async (opt = {}) => {
    const defaultOpt = {
      pageName: '',
      realTimeFlag: true,
      eventName: ''
    }
    const resOpt = {
      ...defaultOpt,
      ...opt
    }
    return await trigger('webStatistics', JSON.stringify(resOpt))
  }
  // 打开app查看图片 img=图片数组，index=当前查看下标
  static nativeShowImage = async (img, index) => {
    return await trigger('nativeShowImage', JSON.stringify(img), Number(index))
  }
  // 客户端toast提示
  static showAppToast = async (message = '') => {
    return await trigger('showToast', message)
  }
  // 打开APP loading
  static showAppWaiting = async () => {
    return await trigger('showWaiting')
  }
  // 关闭APP loading
  static hideAppWaiting = async () => {
    return await trigger('hideWaiting')
  }
  // 登录
  static toLogin = async (isReloadOnSuccess = false) => {
    return await trigger('toLogin', isReloadOnSuccess)
  }
  static appAjax = async (configs = {}) => {
    var defaults = {
        type: 'GET',
        url: '',
        dataType: 'json',
        waiting: '',
        params: {},
        success: null,
        error: null,
        complete: null
      },
      options = {}
    for (var i in defaults) {
      options[i] = configs.hasOwnProperty(i) ? configs[i] : defaults[i]
    }
    var j2p = function (json) {
      var a = []
      for (var i in json) a.push(i + '=' + json[i])
      return a.join('&')
    }
    var random = parseInt(Math.random() * 1000000000000 + 1000000000000)
    var success = '', error = '', complete = ''
    if (options.success) {
      success = 'APP_CALLBACK_SUCCESS_' + random
      window[success] = function (response) {
        if (typeof response == 'string' && options.dataType != 'string') {
          response = JSON.parse(response)
        }
        options.success && options.success.call(window, response)
      }
    }
    if (options.error) {
      error = 'APP_CALLBACK_ERROR_' + random
      window[error] = function () {
        options.error && options.error.call(window)
      }
    }
    if (options.complete) {
      complete = 'APP_CALLBACK_COMPLETE_' + random
      window[complete] = function () {
        options.complete && options.complete(window)
      }
    }

    var params = {
      type: options.type.toUpperCase(),
      url: options.url,
      waiting: options.waiting,
      params: j2p(options.params),
      success: success,
      error: error,
      complete: complete
    }
    return await trigger('ajax', JSON.stringify(params))
  }
}
